package cn.edu.scau.cmi.ema.service;

import cn.edu.scau.cmi.ema.base.CmiPagination;
import cn.edu.scau.cmi.ema.domain.Event;
import cn.edu.scau.cmi.ema.domain.Food;
import cn.edu.scau.cmi.ema.domain.Video;
import cn.edu.scau.cmi.ema.service.base.CmiEmaService;
import cn.edu.scau.cmi.ema.util.CmiSqlUtil;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.Query;
import java.util.*;
@Service("VideoService")
@Transactional

public class VideoServiceImpl extends CmiEmaService implements VideoService {
	public VideoServiceImpl() {
	}

	@Transactional
	public Video saveVideo(Video video) {

		if (video.getId() == null) {
			Event event = eventDAO.findEventById(video.getEvent().getId());
			Food food = foodDAO.findFoodById(video.getFood().getId());

			Video existingVideo = videoDAO.findVideoByPhysicalPrimaryKey(video.getName(), video.getPath());

			video.setEvent(event);
			video.setFood(food);

			if (isEquals(video, existingVideo)) {
				return existingVideo;
			}

			video = videoDAO.store(video);
			videoDAO.flush();

		} else {
			Video existingVideo = videoDAO.findVideoByPrimaryKey(video.getId());

			video = videoDAO.store(video);
			videoDAO.flush();
		}

		return video;
	}

	public void deleteVideo(Video video) {
		videoDAO.remove(video);
		videoDAO.flush();
	}

	@Transactional
	public void deleteVideos(Set<Integer> deleteVideosId) {
		Query query = videoDAO.createNamedQuery("deleteVideosById", -1, -1);
		query.setParameter(1, deleteVideosId);
		query.executeUpdate();
	}

	@Transactional
	public Set<Video> loadVideos() {
		return videoDAO.findAllVideos();

	}

	@Transactional
	public Set<Video> loadReferenceVideos(Set<Video> videos) {
		Iterator<Video> videosIterator = videos.iterator();
		Set<Video> referencedVideos = new HashSet<>();
		while (videosIterator.hasNext()) {
			Video currentVideo = videosIterator.next();

		}
		return referencedVideos;
	}

	public Set<Video> loadVideosByIdSet(Set<Integer> videoIdSet) {

		Iterator<Integer> videoIdIterator = videoIdSet.iterator();
		Set<Video> videoSet = new HashSet<>();
		while (videoIdIterator.hasNext()) {
			Integer id = videoIdIterator.next();
			Video currentVideo = videoDAO.findVideoById(id);
			videoSet.add(currentVideo);
		}
		return videoSet;
	}

	@Transactional
	public List<Video> findAllVideos(Integer startResult, Integer maxRows) {
		return new java.util.ArrayList<Video>(videoDAO.findAllVideos(startResult, maxRows));
	}

	@Transactional
	public Video findVideoByPrimaryKey(Integer id) {
		return videoDAO.findVideoByPrimaryKey(id);
	}

	@Transactional
	public Integer countVideos() {
		return ((Long) videoDAO.createQuerySingleResult("select count(o) from Video o").getSingleResult()).intValue();
	}

	@Transactional
	public Integer countVideos(CmiPagination page) {
		String sql = CmiSqlUtil.createCountHql(page, Video.class);
		return ((Long) videoDAO.createQuerySingleResult(sql).getSingleResult()).intValue();
	}

	/**
	 * search for name with ajax
	 *
	 */
	@Transactional
	public Integer countVideosByName(String queryName) {
		Query query = videoDAO.createNamedQuery("countVideosByName", -1, -1);
		query.setParameter(1, queryName);
		return new Long((long) query.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countVideosByDetachedCriteria(CmiPagination page) {
		DetachedCriteria detachedCriteria = CmiSqlUtil.createDetachedCriteria(page, Video.class);
		Session session = (Session) entityManager.getDelegate();
		detachedCriteria.setProjection(Projections.rowCount());
		return new Long((long) detachedCriteria.getExecutableCriteria(session).uniqueResult()).intValue();
	}

	public Map<String, ?> loadVideoObjectReferencedSet(Video video) {
		HashMap<String, Object> objectReferencedSetMap = new HashMap<>();
		if (video.getEvent() != null) {

			Set<Integer> eventIds = new HashSet<Integer>();
			eventIds.add(video.getEvent().getId());
			objectReferencedSetMap.put("eventIds", eventIds);
		}
		if (video.getFood() != null) {

			Set<Integer> foodIds = new HashSet<Integer>();
			foodIds.add(video.getFood().getId());
			objectReferencedSetMap.put("foodIds", foodIds);
		}

		return objectReferencedSetMap;
	}

	public Map<String, ?> loadVideoClassReferencedSet(Video video) {
		HashMap<String, Object> classReferencedSetMap = new HashMap<>();
		classReferencedSetMap.put("events", eventDAO.findAllEvents());
		classReferencedSetMap.put("foods", foodDAO.findAllFoods());

		return classReferencedSetMap;
	}

	public boolean isEquals(Video video, Object obj) {
		if (obj == video)
			return true;
		if (!(obj instanceof Video))
			return false;
		Video comparedVideo = (Video) obj;
		if (!CheckPropertyEqual(video.getName(), comparedVideo.getName())) {
			return false;
		}
		if (!CheckPropertyEqual(video.getPath(), comparedVideo.getPath())) {
			return false;
		}
		return true;
	}

	public static <T> boolean CheckPropertyEqual(T originProperty, T comparedProperty) {
		// 基本类型经过参数传递后会自动装箱
		String[] className = originProperty.getClass().getName().split("\\.");
		if (className[0].equals("java") && className[1].equals("math")) {
			return ((Comparable) originProperty).compareTo(comparedProperty) == 0 ? true : false;
		} else {
			return originProperty.equals(comparedProperty);
		}
	}
}

